package models;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.config.CacheType;
import com.aton.db.SessionFactory;
import com.aton.util.MixHelper;

import enums.WdOrderTaskStatus;
import enums.WdShareTaskStatus;
import enums.WdTaskStatus;
import mobile.vo.Result;
import models.mappers.UserIngotRecordMapper;
import models.mappers.WdOrderTaskMapper;
import models.mappers.WdShareTaskMapper;
import models.mappers.WdTaskMapper;
import models.mappers.fund.BuyerDepositRecordMapper;
import play.cache.Cache;
import vos.Page;
import vos.SellerBalanceVo;
import vos.TaskSearchVo;
import vos.WdShareTaskSearchVo;

public class WdShareTask {
	
	private static final Logger log = LoggerFactory.getLogger(Task.class);

	public Long id;
	public Long buyerId;
	public Long taskId;
	public Long orderCount;
	public Long baseCommission;
	public String baseCommissionStr;
	public String taskIdStr;
	public String itemPic;
	public String picUrl;
	public String itemTitle;
	public String itemUrl;
	public Long comminssion;
	public String cacPicUrl;
	public WdShareTaskStatus status;
	public String statusTxt;
	public Date takeTime;
	public String takeTimeStr;
	public Date modifyTime;
	public String remark;
	public Date orderDeadline;
	public Long itemPrice;
	
	public String idStr;
	
	public String qq;
	public Long cashback;
	public String cashbackStr;
	public String other;
	public String shareText;
	public String shareImageUrls;
	
	public Long waitCheckCount;
	public Long refundedCount;
	public Long disallowedCount;
	public Long finishedCount;

	public String taskNo;
	
	
	/**
	 * 领取任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 */
	public Result save(){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			this.status = WdShareTaskStatus.RECEIVED;
			this.takeTime = new Date();
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdTaskMapper  wdTaskMapper = sqlSession.getMapper(WdTaskMapper.class);
			//查询当前任务是否存在
			WdTask mainTask = wdTaskMapper.findById(this.taskId);
			if(mainTask==null||(mainTask.totalShareCount-mainTask.takeCount)<0){
				return Result.errorWithMsg("当前任务不存在或已无领取名额");
			}
			this.comminssion = new BigDecimal(mainTask.baseCommission * 0.8).longValue();
			//查询当前任务是否被领取
			int count = wdShareTaskMapper.takeCount(taskId, buyerId);
			
			if(count>0){
				return Result.errorWithMsg("已领取过当前任务");
			}
			
			mainTask.takeCount += 1;
			
			wdTaskMapper.updateTakeCount(mainTask);
			
			wdShareTaskMapper.takeTask(this);
			
			sqlSession.commit();
			
			WdShareTask showTask = wdShareTaskMapper.getShowTask(this.id, this.buyerId);
			
			return Result.optSuccessWithData(showTask);
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("领取任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("任务领取失败~~");
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 查询已领取的任务列表
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param vo
	 * @return
	 */
	public static Page<WdShareTask> listBuyerTask(TaskSearchVo vo){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			int count = wdShareTaskMapper.countBuyerTask(vo);
			if(count==0){
				return Page.EMPTY;
			}
			Page<WdShareTask> p = Page.newInstance(vo.pageNo, vo.pageSize, count);
			p.items = wdShareTaskMapper.listBuyerTask(vo);
			for(WdShareTask obj : p.items){
				obj.values();
			}
			return p;
		}finally {
			sqlSession.close();
		}
	}
	
	public void values(){
		this.taskIdStr = String.valueOf(this.taskId);
		if(this.status == WdShareTaskStatus.SUMITED){
			SqlSession sqlSession = SessionFactory.getSqlSession();
			try{
				WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
				Integer count = mapper.countDisallowed(this.id);
				if(count>0){
					this.status = WdShareTaskStatus.ORDER_DISALLOWED;
				}
			}finally {
				sqlSession.close();
			}
		}
		if(this.status!=null){
			this.statusTxt = this.status.title;
		}
	}
	
	/**
	 * 查询微代分享任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param taskId
	 * @return
	 */
	public static WdShareTask getWdShareTaskById(Long taskId, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return  wdShareTaskMapper.getShowTask(taskId, buyerId);
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 取消任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @return
	 */
	public static Result cancelWdTask(Long taskId, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdTaskMapper wdTaskMapper = sqlSession.getMapper(WdTaskMapper.class);
			
			WdShareTask wdShareTask = wdShareTaskMapper.getShareTask(taskId, buyerId);
			if(wdShareTask==null){
				return Result.errorWithMsg("要取消的任务不存在");
			}
			
			WdTask wdTask = wdTaskMapper.findById(wdShareTask.taskId);
			wdTask.takeCount -= 1;
			wdTaskMapper.update(wdTask);
			
			wdShareTaskMapper.updateTaskStatus(wdShareTask.id, WdShareTaskStatus.CANCLED);
			
			// 如果该任务状态为待结算状态，及返回分享任务的佣金
			log.info("主任务状态为待结算状态，返还任务佣金到用户金币账户");
			if(wdTask.status==WdTaskStatus.WAIT_BALANCE){
				UserIngotRecordMapper userIngotRecordMapper = sqlSession.getMapper(UserIngotRecordMapper.class);
				UserIngotRecord lastRecord =  userIngotRecordMapper.selectLastRecord(wdTask.sellerId);
				
				UserIngotRecord recode = UserIngotRecord.newInstance(wdTask.sellerId, lastRecord);
				String memo = MixHelper.format("买手取消任务{}-{}，返还任务佣金", wdShareTask.taskId, wdShareTask.id);
				recode.createTime(new Date()).plus(wdTask.baseCommission).taskId(wdTask.id).memo(memo);
				userIngotRecordMapper.insert(recode);
			}
			
			sqlSession.commit();
			
			Cache.safeDelete(CacheType.USER_INFO.getKey(wdTask.sellerId));
			
			return Result.optSuccess();
			
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("取消任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("取消领取失败~~");
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 删除微代任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param taskId
	 * @param buyerId
	 */
	public static void delTask(Long taskId, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			wdShareTaskMapper.delBuyerTask(taskId, buyerId);;
			sqlSession.commit();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("取消任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("取消领取失败~~");
		}finally {
			sqlSession.close();
		}
	}
	
	
	/**
	 * 更新任务状态
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param id
	 * @param picUrl
	 * @param buyerId
	 */
	public static void processWdTask(Long id, String picUrl, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			wdShareTaskMapper.processWdTask(id, picUrl, buyerId);
			sqlSession.commit();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("取消任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("取消领取失败~~");
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 统计需要审核的任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param sellerId
	 * @return
	 */
	public static int countWaitCheckTask(Long sellerId){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdShareTaskSearchVo vo = new WdShareTaskSearchVo();
			vo.sellerId = sellerId;
			return wdShareTaskMapper.countWaitCheckTask(vo);
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 查询待审核的任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @return
	 */
	public static Page<WdShareTask> listWaitCheckShareTask(WdShareTaskSearchVo vo){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			
			int count = wdShareTaskMapper.countWaitCheckTask(vo);
			if(count==0){
				return Page.EMPTY;
			}
			Page<WdShareTask> p = Page.newInstance(vo.pageNo, vo.pageSize, count);
			
			p.items = wdShareTaskMapper.listWaitCheckTask(vo);
			
			for(WdShareTask obj: p.items){
				obj.values();
			}
			
			return p;
			
		}finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param taskId
	 * @param id
	 */
	public static void checkShareTask(Long taskId, Long id, Boolean rejected){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdShareTaskStatus status = null;
			if(!rejected){
				status = WdShareTaskStatus.WAIT_CONFIRM_REFUND;
			}else{
				status = WdShareTaskStatus.SHARE_DISALLOWED;
			}
			wdShareTaskMapper.checkShareTask(taskId, id, status);
			sqlSession.commit();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("确认返佣时发生异常：{}", ex.getMessage());
			throw new RuntimeException("确认返佣失败~~");
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 确认返佣操作
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月5日
	 * @param taskId
	 * @param buyerId
	 */
	public static Result confirmRefund(Long taskId, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdTaskMapper wdTaskMapper = sqlSession.getMapper(WdTaskMapper.class);

			WdShareTask wdShareTask = wdShareTaskMapper.getShareTask(taskId, buyerId);
			WdTask wdTask = wdTaskMapper.findById(wdShareTask.taskId);

			if(wdShareTask==null||wdShareTask.status != WdShareTaskStatus.WAIT_CONFIRM_REFUND){
				log.error("分享任务{}不存在或任务状态错误", taskId);
				return Result.errorWithMsg("任务不存在或任务状态不正确");
			}
			//更新任务状态,如果当前主任务已过订单提交期，则更新分享任务为已完成
			if(wdTask.orderDeadline.before(new Date())){
				wdShareTaskMapper.updateTaskStatus(wdShareTask.id, WdShareTaskStatus.FINISHED);
			}else {
				wdShareTaskMapper.updateTaskStatus(wdShareTask.id, WdShareTaskStatus.WAIT_SUBMIT);
			}
			
			//发放佣金
			UserIngotRecordMapper ingotMapper = sqlSession.getMapper(UserIngotRecordMapper.class);
			UserIngotRecord lastRecord = ingotMapper.selectLastRecord(buyerId);
			StringBuilder sb = new StringBuilder();
			String memo = MixHelper.format("微代任务编号：{}-{} 分享任务已完成，获得佣金", wdShareTask.taskId, wdShareTask.id);
			UserIngotRecord record = UserIngotRecord.newInstance(buyerId, lastRecord).plus(wdShareTask.comminssion).memo(memo)
					.isReward(true).taskId(wdShareTask.taskId).createTime(new Date());
			ingotMapper.insert(record);

			sqlSession.commit();
			
			User.findByIdWichCache(buyerId).ingot(record.balance).updateCache();
			
			return Result.optSuccess();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("确认返佣时发生异常：{}", ex.getMessage());
			throw new RuntimeException("确认返佣失败~~");
		}finally{
			sqlSession.close();
		}
	}
		
	/**
	 * 查询需要提交订单的分享任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月5日
	 * @param id
	 * @param buyerId
	 * @return
	 */
	public static WdShareTask getWaitSubmitOrderShareTask(Long id, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return wdShareTaskMapper.getWaitSubmitOrderShareTask(id, buyerId);
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 提交订单
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月5日
	 * @param id
	 * @param orderNosStr
	 * @param buyerId
	 * @return
	 */
	public static Result submitOrders(Long id, String orderNosStr, long buyerId) {
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdOrderTaskMapper wdOrderTaskMapper  = sqlSession.getMapper(WdOrderTaskMapper.class);
			
			WdShareTask wdShareTask  = wdShareTaskMapper.getWaitSubmitOrderShareTask(id, buyerId);
			if(wdShareTask==null){
				return Result.errorWithMsg("未找到任务");
			}
			
			String[] orderNos = orderNosStr.split(",");
			WdOrderTask obj = null;
			String orderNo = null;
			for(String tmpOrderNo : orderNos){
				
				if(tmpOrderNo==null||"".equals(tmpOrderNo.trim())){
					continue;
				}
				orderNo = tmpOrderNo.trim();
				if(wdOrderTaskMapper.getTaskByOrderNo(orderNo)!=null){
					sqlSession.rollback();
					return Result.errorWithMsg(MixHelper.format("订单【{}】已存在，请更正后重试!", orderNo));
				}
				obj = new WdOrderTask();
				obj.buyerId = buyerId;
				obj.taskId = wdShareTask.taskId;
				obj.shareId = wdShareTask.id;
				obj.status = WdOrderTaskStatus.WAIT_CHECK;
				obj.orderNo = orderNo;
				obj.createTime = new Date();
				wdOrderTaskMapper.insert(obj);
			}
			
			sqlSession.commit();
			
			return Result.optSuccess();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error(ex.getMessage());
			throw new RuntimeException("保存订单时发生异常！！");
		}finally{
			sqlSession.close();
		}
	}

	public static List<WdShareTask> listOverdueTask() {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper mapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return mapper.listOverdueTask();
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 查询已完成的任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月7日
	 * @return
	 */
	public static List<WdShareTask> listFinishedTask() {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper mapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return mapper.listFinishedTask();
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 完成任务
	 */
	public void finishTask() {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper mapper = sqlSession.getMapper(WdShareTaskMapper.class);
			mapper.finishTask(id);
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 查询任务列表
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月7日
	 * @param vo
	 * @return
	 */
	public static Page<WdShareTask> listBuyerTaskForSeller(WdShareTaskSearchVo vo) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper mapper = sqlSession.getMapper(WdShareTaskMapper.class);
			int count = mapper.countBuyerWdTaskForSeller(vo);
			if(count==0){
				return Page.newInstance(vo.pageNo, vo.pageSize, count);
			}
			
			Page<WdShareTask> page = Page.newInstance(vo.pageNo, vo.pageSize, count);
			page.items = mapper.listBuyerWdTaskForSeller(vo);
			for(WdShareTask obj: page.items){
				obj.values();
			}
			return page;
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 保存微代任务一
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月15日
	 * @param id
	 * @param picUrl
	 * @param buyerId
	 */
	public static void saveWdTaskStepOne(Long id, String picUrl, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			wdShareTaskMapper.saveWdTaskStepOne(id, picUrl, buyerId);
			sqlSession.commit();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("取消任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("保存任务失败~~");
		}finally {
			sqlSession.close();
		}
	}

	/**
	 * 更新分享任务状态
	 * WAIT_SUBMIT("待提交订单")->SUMITED("订单待审核"),
	 */
    public static void updateLiveTaskStatus() {
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			wdShareTaskMapper.updateLiveTaskStatus();
			sqlSession.commit();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("更新分享任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("保存任务失败~~");
		}finally {
			sqlSession.close();
		}
    }

	/**
	 * 统计账单
	 * @param vo
	 * @return
	 */
	public static Page<WdShareTask> findBuyerTaskBalance(SellerBalanceVo vo) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			int totalCount = wdShareTaskMapper.countBuyerTaskBalance(vo);
			Page<WdShareTask> page = Page.newInstance(vo.pageNo,vo.pageSize, totalCount);
			if(totalCount==0){
				return page;
			}
			page.items = wdShareTaskMapper.findBuyerTaskBalance(vo);
			return page;
		}finally {
			sqlSession.close();
		}
	}

	/**
	 * 导出微代对账单
	 * @param vo
	 * @return
	 */
	public static List<WdShareTask> exportSellerBlance(SellerBalanceVo vo) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return wdShareTaskMapper.exportSellerBlance(vo);
		}finally {
			sqlSession.close();
		}
	}

	/**
	 * 查询申请页显示页面
	 */
	public static WdShareTask findBuyerTaskDetailForView(Long id, Long buyerId){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			return wdShareTaskMapper.findBuyerTaskDetailForView(id, buyerId);
		}finally {
			sqlSession.close();
		}
	}

	/**
	 * 取消微代任务 （管理员使用）
	 * @param taskId
	 * @return
	 */
	public static Result cancelWdTask(Long taskId){
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
			WdTaskMapper wdTaskMapper = sqlSession.getMapper(WdTaskMapper.class);

			WdShareTask wdShareTask = wdShareTaskMapper.getShareTaskById(taskId);
			if(wdShareTask==null){
				return Result.errorWithMsg("要取消的任务不存在");
			}
			//取消订单？？？？

			WdTask wdTask = wdTaskMapper.findById(wdShareTask.taskId);
			wdTask.takeCount -= 1;
			wdTaskMapper.update(wdTask);

			wdShareTaskMapper.updateTaskStatus(wdShareTask.id, WdShareTaskStatus.CANCLED);

			// 如果该任务状态为待结算状态，及返回分享任务的佣金
			log.info("主任务状态为待结算状态，返还任务佣金到用户金币账户");
			if(wdTask.status==WdTaskStatus.WAIT_BALANCE){
				UserIngotRecordMapper userIngotRecordMapper = sqlSession.getMapper(UserIngotRecordMapper.class);
				UserIngotRecord lastRecord =  userIngotRecordMapper.selectLastRecord(wdTask.sellerId);

				UserIngotRecord recode = UserIngotRecord.newInstance(wdTask.sellerId, lastRecord);
				String memo = MixHelper.format("买手取消任务{}-{}，返还任务佣金", wdShareTask.taskId, wdShareTask.id);
				recode.createTime(new Date()).plus(wdTask.baseCommission).taskId(wdTask.id).memo(memo);
				userIngotRecordMapper.insert(recode);
			}
			sqlSession.commit();
			Cache.safeDelete(CacheType.USER_INFO.getKey(wdTask.sellerId));
			return Result.optSuccess();
		}catch(Exception ex){
			sqlSession.rollback();
			log.error("取消任务时发生异常：{}", ex.getMessage());
			throw new RuntimeException("取消领取失败~~");
		}finally {
			sqlSession.close();
		}
	}
}
